<template>
  <Select @dropdown-visible-change="handleFetch" v-bind="$attrs" @change="handleChange" :filter-option="filterOption" :options="getOptions" v-model:value="state">
    <template #[item]="data" v-for="item in Object.keys($slots)">
      <slot :name="item" v-bind="data || {}"></slot>
    </template>
    <template #suffixIcon v-if="loading">
      <LoadingOutlined spin />
    </template>
    <template #notFoundContent v-if="loading">
      <span>
        <LoadingOutlined spin class="mr-1" />
        {{ t('component.form.apiSelectNotFound') }}
      </span>
    </template>
  </Select>
</template>
<script lang="ts">
import { defineComponent, PropType, ref, watchEffect, computed, unref, watch } from 'vue';
import { Select } from 'ant-design-vue';
import { isFunction, get, omit } from '@pkg/utils';
import { useRuleFormItem } from '@/hooks/component/use-form-item';
import { LoadingOutlined } from '@ant-design/icons-vue';
import { useI18n } from '@pkg/locale';
import { useAttrs } from '@pkg/use';
import { useUserStore } from '@/store/user';
import { request } from '@pkg/request/src';
type OptionsItem = { label: string; value: string; disabled?: boolean };

export default defineComponent({
  name: 'ApiSelect',
  components: {
    Select,
    LoadingOutlined,
  },
  inheritAttrs: false,
  props: {
    value: [Array, Object, String, Number],
    //选项值数字转字符串
    numberToString: { type: Boolean },
    //选项值字符转数字
    stringToNumber: { type: Boolean },
    api: {
      type: [String, Function],
      default: null,
    },
    //字典code(和api二选一,优先使用)
    dictCode: {
      type: [String] as PropType<string>,
      default: '',
    },
    // 接口参数
    params: {
      type: Object as PropType<Recordable>,
      default: () => ({}),
    },
    // 支持 xxx.xxx.xx
    resultField: { type: String, default: '' },
    labelField: { type: String, default: 'label' },
    valueField: { type: String, default: 'value' },
    immediate: { type: Boolean, default: true },
    alwaysLoad: { type: Boolean, default: false },
  },
  emits: ['options-change', 'change'],
  setup(props, { emit }) {
    const options = ref<OptionsItem[]>([]);
    const loading = ref(false);
    const isFirstLoad = ref(true);
    const emitData = ref<any[]>([]);
    const attrs = useAttrs();
    const { t } = useI18n();

    // 嵌入到表单中，只需使用挂钩绑定来执行表单验证
    const [state] = useRuleFormItem(props, 'value', 'change', emitData);

    const getOptions = computed(() => {
      const { labelField, valueField, numberToString, stringToNumber } = props;

      return unref(options).reduce((prev, next: Recordable) => {
        if (next) {
          let value = next[valueField];
          if (stringToNumber) {
            value = Number(value);
          }
          prev.push({
            ...omit(next, [labelField, valueField]),
            label: next[labelField],
            value: numberToString ? `${value}` : value,
          });
        }
        return prev;
      }, [] as OptionsItem[]);
    });

    watchEffect(() => {
      props.immediate && !props.alwaysLoad && fetch();
    });

    watch(
      () => props.params,
      () => {
        !unref(isFirstLoad) && fetch();
      },
      { deep: true },
    );

    async function fetch() {
      const dictCode = props.dictCode;
      if (dictCode) {
        //使用字典作为选项值
        options.value = useUserStore().getDictData[dictCode];
        return;
      }
      let api: any = props.api;
      if (!api) return;
      options.value = [];
      try {
        loading.value = true;
        let res = {};
        if (!isFunction(api)) {
          res = await getList(props.api, props.params);
        } else {
          res = await api(props.params);
        }
        if (Array.isArray(res)) {
          options.value = res;
          emitChange();
          return;
        }
        if (props.resultField) {
          options.value = get(res, props.resultField) || [];
        }
        emitChange();
      } catch (error) {
        console.warn(error);
      } finally {
        loading.value = false;
      }
    }

    async function handleFetch(visible) {
      if (visible) {
        if (props.alwaysLoad) {
          await fetch();
        } else if (!props.immediate && unref(isFirstLoad)) {
          await fetch();
          isFirstLoad.value = false;
        }
      }
    }

    /**
     * 数据查询过滤
     * @param input
     * @param option
     */
    const filterOption = (input: string, option: any) => {
      return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };

    function emitChange() {
      emit('options-change', unref(getOptions));
    }

    function handleChange(_, ...args) {
      emitData.value = args;
    }

    /**
     *
     * @param url
     * @param params
     */
    async function getList(url, params?) {
      return request.get({ url: url, params }, { successMessageMode: 'none' });
    }

    return {
      state,
      attrs,
      getOptions,
      loading,
      filterOption,
      t,
      handleFetch,
      handleChange,
    };
  },
});
</script>
